package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WmChannelService wmChannelService;
    @Autowired
    private WmNewsService wmNewsService;
    /**
     * 查询所有频道
     *
     * @return
     */
    @Override
    public ResponseResult findAll() {
        //优化思路： 使用redis缓存频道列表数据
        //先查缓存
        String channelsJSON = cacheService.get("channels");
        //缓存有：直接返回
        if (!StringUtils.isEmpty(channelsJSON)){
            List channels = JSON.parseObject(channelsJSON, List.class);
            return ResponseResult.okResult(channels);
        }else{
            //缓存没有：查询数据库，并添加到缓存
            List<WmChannel> channels = list();
            cacheService.set("channels",JSON.toJSONString(channels));
            return ResponseResult.okResult(channels);
        }
    }

    /**
     * 删除频道
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {

        // 校验前端参数
        if(id == null){
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        WmChannel wmChannel = getById(id);
        // 被引用也不能删除
//        int count = wmChannelService.count(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getId, wmChannel.getId())
//                .eq(WmChannel::getStatus, wmChannel.getStatus()));
//        if (count > 0){
//            // 被引用了，不能删除
//            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
//        }


        // 只有状态为0：禁用状态下才能删除   0:禁用  1：启用

        if (wmChannel.getStatus().equals(1)){
            // 启用状态不能删除
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }else{
            removeById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    /**
     * 根据频道名称模糊分页查询
     * @param wmChannelDto
     * @return
     */
    @Override
    public ResponseResult findByPage(WmChannelDto wmChannelDto) {
        // 校验参数
        if(wmChannelDto == null){
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // 分页
        IPage page = new Page(wmChannelDto.getPage(),wmChannelDto.getSize());

        // 名称可以模糊查询:构建模糊查询的wrapper
        LambdaQueryWrapper<WmChannel> wrapper = new LambdaQueryWrapper<>();
        // 校验前端传来的名称是否为空


            // 不为空,名称模糊查询
        wrapper.like(WmChannel::getName,wmChannelDto.getName());

            page = page(page,wrapper);
            // 封装返回对象
            ResponseResult responseResult = new PageResponseResult(wmChannelDto.getPage(),wmChannelDto.getSize(),(int)page.getTotal());
            responseResult.setData(page.getRecords());
            return responseResult;
        }


    /**
     * 新增频道
     * @param wmChanneldto
     * @return
     */
    @Override
    public ResponseResult insert(WmChannel wmChanneldto) {
        // 1.校验参数
        if (wmChanneldto == null){
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // 2.名字重复不能保存
        // 构建查询条件
        WmChannel wmchannel = getOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getName, wmChanneldto.getName()));
        if (wmchannel!=null){
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        // 3.保存
        WmChannel wmChannel1 = new WmChannel();
        BeanUtils.copyProperties(wmChanneldto,wmChannel1);

        wmChannel1.setIsDefault(true);
        wmChannel1.setCreatedTime(new Date());
        save(wmChannel1);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult reNew(WmChannel wmChannel) {
        // 1.校验参数
            if (wmChannel == null || wmChannel.getId() == null){
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
        // 2.被引用的频道不能禁用
        // 构建查询条件
        int count = wmNewsService.count(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, wmChannel.getId())
                .eq(WmNews::getStatus, WmNews.Status.PUBLISHED.getCode()));
            if (count > 0){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            updateById(wmChannel);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
